<template>
  <div class="container">
    <div class="topBox">
      <div class="title">
        <p class="subtitle">自定义合同模板（编辑中）</p>
      </div>
      <div class="btnBox">
        <el-button class="commonBut saveBtn funComBut quitBtn" @click="quitEdit"
          >退出编辑</el-button
        >
        <el-button class="commonBut saveBtn funComBut" @click="saveTemplate"
          >保存</el-button
        >
      </div>
    </div>
    <div class="mainCon">
      <el-row>
        <el-col :span="16">
          <UE
            :id="id"
            :config="config"
            ref="ue"
            class="ueditorBox"
            v-on:ready="ready"
            v-bind:value="defaultMsg"
            v-on:input="inputChange"
          ></UE>
        </el-col>
        <el-col :span="8">
          <div class="paramsBox">
            <p class="title">可添加字段</p>
            <div class="search">
              <el-input
                placeholder="请输入字段名称"
                clearable
                v-model="fieldName"
                class="screenInp"
              ></el-input>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchFieldName"
                class="commonBtn screenBtn"
              ></el-button>
            </div>
            <el-collapse v-model="activeNames">
              <el-collapse-item
                v-for="item in filterList"
                :title="item.title"
                :name="item.title"
                :key="item.title"
              >
                <el-button
                  class="colBtn"
                  type="primary"
                  v-for="v in item.params"
                  :key="v.id"
                  @click="setItems(v)"
                  >{{ v.name }}<i class="el-icon-circle-plus-outline"></i
                ></el-button>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      title="温馨提示"
      :visible.sync="confirmDialogVisible"
      width="40%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <span
        ><i class="icon iconfont iconshengming"></i> 退出编辑后<span
          style="color: #e02020"
          >不保存新增内容</span
        >，是否确认继续？
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button class="btn cancel" @click="confirmDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" class="btn save" @click="handleConfirm()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import UE from '@/components/publicCom/ueditor.vue'

export default {
  name: 'editContractTemplate',
  data() {
    return {
      confirmDialogVisible: false,
      confirmLeave: false,
      fieldName: '',
      // 初始化Ueditor配置参数
      config: {
        initialFrameWidth: null,
        initialFrameHeight: 610,
        autoHeightEnabled: false, //高度自适应
        wordCount: true, //是否开启字数统计
        enableAutoSave: false, //自动保存功能
        elementPathEnabled: false,
        toolbars: [
          [
            '|',
            'undo',
            'redo',
            '|',
            'bold',
            'italic',
            'underline',
            'fontborder',
            'removeformat',
            'pasteplain',
            '|',
            'forecolor',
            'backcolor',
            'insertorderedlist',
            'insertunorderedlist',
            'cleardoc',
            '|',
            'customstyle',
            'paragraph',
            'fontfamily',
            'fontsize',
            '|',
            'indent',
            '|',
            'justifyleft',
            'justifycenter',
            'justifyright',
            'justifyjustify',
            '|',
            'link',
            'unlink',
            '|',
            'horizontal',
            '|',
            //增加图片上传
            'simpleupload',
            'insertimage',
            '|',
            'preview',
            'searchreplace',
            'drafts',
          ],
        ],
        imageScaleEnabled: false,
        // enterTag:'br',
      },
      // 不同编辑器必须不同的id
      id: 'templateEditor',
      defaultMsg: "<h3 style='text-align:center;'> 《农民工简易劳务合同》</h3>", //富文本编辑器初始数据
      newMsg: "<h3 style='text-align:center;'> 《农民工简易劳务合同》</h3>",
      tagList: [],
      filterList: [],
      activeNames: [], //面板展开
    }
  },
  components: {
    UE,
  },
  async mounted() {
    await this.getAllTag()
    this.searchFieldName()
    window.addEventListener('beforeunload', this.leaveConfirm)
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.confirmLeave = false
      window.addEventListener('beforeunload', vm.leaveConfirm)
      vm.getTemplateHtml() //获取自定义模板
    })
  },
  beforeRouteLeave(to, from, next) {
    // console.log(this.newMsg)
    if (this.newMsg === this.defaultMsg || this.confirmLeave) {
      this.confirmDialogVisible = false
      window.removeEventListener('beforeunload', this.leaveConfirm)
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/baseSettings/viewContractTemplate',
        newUrl: this.$router.currentRoute.fullPath,
      })
      next()
    } else {
      this.confirmDialogVisible = true
      next(false)
    }
  },
  methods: {
    // 获取自定义模板
    getTemplateHtml() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/contracttemp/getTemp',
      })
        .then((response) => {
          if (!response.data.hasError) {
            if (response.data.result && response.data.result.data) {
              this.defaultMsg = response.data.result.data
              this.newMsg = response.data.result.data
            }
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 获取标签
    getAllTag() {
      return this.axios({
        method: 'post',
        url: 'api-e/cs/contracttag/allTag',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const tagList = response.data.result
            const activeNames = []
            tagList.forEach((item) => {
              if (item.params) {
                item.params.forEach((v) => {
                  if (v.name) {
                    v.name = v.name.replace(/#/g, '')
                  }
                })
              }
              activeNames.push(item.title)
            })
            this.tagList = tagList
            this.activeNames = activeNames
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 搜索标签
    searchFieldName() {
      this.filterList = JSON.parse(JSON.stringify(this.tagList))
      this.filterList.forEach((item) => {
        item.params = item.params.filter((v) => {
          if (v.name.indexOf(this.fieldName) > -1) {
            return v
          }
        })
      })
    },
    // 富文本编辑输入回调
    inputChange(val) {
      this.newMsg = val.content
    },
    // 页面关闭或者刷新提示
    leaveConfirm(e) {
      e = e || window.event
      if (e && this.newMsg !== this.defaultMsg) {
        e.returnValue = '关闭提示'
      }
    },
    // 退出编辑
    quitEdit() {
      this.$router.push({
        name: 'viewContractTemplate',
        path: '/home/baseSettings/viewContractTemplate',
      })
    },
    // 确认退出
    handleConfirm() {
      this.confirmLeave = true
      this.$router.push({
        name: 'viewContractTemplate',
        path: '/home/baseSettings/viewContractTemplate',
      })
    },
    // 保存模板
    saveTemplate() {
      const contextDemo = this.$refs.ue.getUEContent()
      this.axios({
        method: 'post',
        url: 'api-e/cs/contracttemp/save',
        data: {
          html: contextDemo,
          status: 0,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message.success('操作成功')
            this.handleConfirm()
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 添加标签
    setItems(item) {
      this.$refs.ue.setFocus()
      this.$refs.ue.setContexts(
        `<span style='color: #409EFF;'>#${item.name}#</span>`
      )
    },
    destroyed() {
      window.removeEventListener('beforeunload', this.leaveConfirm)
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  padding: 24px;
  .topBox {
    height: 92px;
    background: #e4ebf1;
    position: relative;
    .title {
      padding: 36px;
      .subtitle {
        font: bold 18px Microsoft YaHei;
        color: #333;
      }
    }
    .btnBox {
      position: absolute;
      right: 24px;
      top: 50%;
      transform: translateY(-50%);
      .quitBtn {
        background: #3d5266;
        border-color: #3d5266;
      }
    }
  }
  .mainCon {
    top: 221px;
    padding: 0;
    .el-row {
      height: calc(100%);
      background-color: #fff;
      .el-col {
        height: calc(100%);
        .ueditorBox {
          height: 100%;
        }
        .paramsBox {
          width: 100%;
          height: 100%;
          padding: 20px;
          .title {
            font: bold 20px Microsoft YaHei;
            color: #3a3a3a;
          }
          .search {
            width: 100%;
            margin-top: 10px;
            .screenBtn {
              display: inline-block;
              width: 36px;
              height: 36px;
            }
            .screenInp {
              display: inline-block;
              width: calc(100% - 56px);
              margin-right: 10px;
            }
          }
          /deep/ .el-collapse {
            border: 0;
            .el-collapse-item {
              margin-top: 12px;
            }
            .el-collapse-item__header {
              font-size: 14px;
              color: #3a3a3a;
              font-weight: 700;
              border: 0;
              background: #f6f8fc;
              padding: 0 10px;
              border-radius: 5px;
              height: 38px;
              line-height: 38px;
            }
            .el-collapse-item__wrap {
              border: 0;
            }
            .el-collapse-item__content {
              padding-bottom: 0;
            }
            .colBtn {
              height: 28px;
              padding: 0 8px;
              line-height: 28px;
              font-size: 14px;
              color: #3a3a3a;
              font-weight: 400;
              background: #eceeef;
              border: #eceeef;
              margin-top: 8px;
              margin-right: 12px;
              margin-left: 0;
              .el-icon-circle-plus-outline {
                font-size: 16px;
                margin-left: 4px;
                color: #3a3a3a;
              }
            }
            .colBtn:first-child {
              margin-top: 12px;
            }
          }
        }
      }
    }
  }
}
/deep/ .el-dialog__header {
  border-bottom: 0;
}
/deep/ .el-dialog__footer {
  background: none;
}
.iconshengming {
  width: 20px;
  height: 20px;
  color: #ffaa00;
}
</style>
